var app = getApp();

var mapControlWidthHeight = 60;

var ifMoving_interval = -1;
var carMarkerID = 999,
    carMarkerIndex = -1,
    duration = 30000;
var nowTime = app.getBeijingTime();
Page({
    data: {
        mapHeight: app.globalData.machineInfo.windowHeight,

        mapCenter: app.globalData.mapCenter,
        mapViewCenter: app.globalData.mapCenter,
        mapViewRegion: {},
        mapScale: app.globalData.mapScale,
        mapViewScale: app.globalData.mapScale,

        mapMarkers: [],
        busStations: [],

        qMapKey: app.globalData.qMapKey,

        ifStarted: false,
        nextMoveTs: 0,
        ifOnline: true,
    },

    onLoad: function(options) {},

    onReady: function() {},

    onShow: function() {

        this.mapCtx = wx.createMapContext('map');
        console.log('地图已加载')

        var that = this;
        console.log('正在加载', app.getBeijingTime().ts % 10000)
        wx.showToast({
            title: '正在加载...',
            icon: 'none',
            duration: 4000,
        })

        setTimeout(function() {
            console.log('首次展示', app.getBeijingTime().ts % 10000)
            that.showBus({
                ifFirstTime: true,
            });

        }, 3900)

        // nowTime = {};
        ifMoving_interval = setInterval(function() {
            nowTime = app.getBeijingTime();
            // console.log('tip时刻', nowTime);

            if (that.data.ifStarted &&
                nowTime.ts > that.data.nextMoveTs && that.data.nextMoveTs > 0) {
                console.log('即将开始下一轮,当前时间', app.getBeijingTime( nowTime.ts).time,
                app.getBeijingTime(  that.data.nextMoveTs).time);

                that.showBus(); //生产环境
            }
        }, 1000);
    },

    showBus: function(e) {
        var that = this;
        nowTime = app.getBeijingTime();
        this.setData({
            nextMoveTs: nowTime.ts + duration,
        })


        //只读取1号GPS的位置
        app.db.collection('jimiGps').where({
                beijingTs: app.db.command.gt(nowTime.ts - 60000),
                data: app.db.command.elemMatch({
                    imei: app.globalData.gpsImei
                })
            }).orderBy('beijingTs', 'desc').limit(2)
            .get({
                success: function(jimiGps_data) {
                    console.log('jimiGps_data', jimiGps_data);
                    jimiGps_data = jimiGps_data.data;

                    if (jimiGps_data.length == 0) {
                        console.log('在线状态',that.data.ifOnline)
                        if (that.data.ifOnline) {
                            that.setData({
                                ifOnline: false, //控制,busOffline只出现一次
                            })
                            that.busOffline();
                        }
                        return;
                    }

                    that.setData({
                        ifOnline: true,
                    })

                    //挑选gps,选imie=app.globalData.gpsImei
                    //默认得到了2组数据
                    for (var i = 0; i < jimiGps_data.length; i++) {
                        for (var j = 0; j < jimiGps_data[i].data.length; j++) {
                            if (jimiGps_data[i].data[j].imei == app.globalData.gpsImei) {
                                jimiGps_data[i].data[j].beijingTime = jimiGps_data[i].beijingTime;
                                jimiGps_data[i].data[j].beijingTs = jimiGps_data[i].beijingTs;
                                jimiGps_data[i] = jimiGps_data[i].data[j];

                                break;
                            }
                        }
                    }
                    if (jimiGps_data.length == 1) {
                        jimiGps_data[1] = jimiGps_data[0];
                    }
                    // console.log('jimiGps_data', jimiGps_data)
                    if (e && e.hasOwnProperty('ifFirstTime')) {
                        //这是第一次获取车的位置,将marker定在第一点,然后向第二点移动

                        carMarkerIndex = 0;

                        that.setData({
                            ifStarted: true,
                            // nextMoveTs: nowTime.ts + 3000, //抬高时间,避免错误的第一步
                            mapMarkers: [{
                                id: carMarkerID,
                                longitude: jimiGps_data[1].longitude,
                                latitude: jimiGps_data[1].latitude,
                                iconPath: '/images/bus/pink.png',
                                width: 40,
                                height: 20,
                                rotate: 0,
                                anchor: { x: 0.5, y: 0.5 }
                            }],

                            mapCenter: {
                                latitude: jimiGps_data[1].latitude,
                                longitude: jimiGps_data[1].longitude,
                            },
                        })
                    }


                    duration = jimiGps_data[0].beijingTs - jimiGps_data[1].beijingTs;
                    if (duration < 10000) {
                        duration = 10000;
                    }
                    console.log('平移开始 云时间', jimiGps_data[0],
                        '手机时间', nowTime.time);

                    that.setData({
                        nextMoveTs: nowTime.ts + duration,
                    })

                    //计算距离
                    var distance = Math.abs(jimiGps_data[0].longitude - jimiGps_data[1].longitude) +
                        Math.abs(jimiGps_data[0].latitude - jimiGps_data[1].latitude);
                    if (distance < 0.00001) {
                        return;
                    }

                    //平移
                    that.mapCtx.translateMarker({
                        markerId: carMarkerID,
                        destination: {
                            latitude: jimiGps_data[0].latitude.toFixed(8),
                            longitude: jimiGps_data[0].longitude.toFixed(8)
                        },
                        autoRotate: false,
                        moveWithRotate: false,
                        rotate:that.getMapMarkerRotate(jimiGps_data[1], jimiGps_data[0]),
                        duration,
                        success: function() {
                            console.log('平移 success', nowTime.time);
                            // that.showBus();
                            nowTime = app.getBeijingTime();
                            //完成了平移,取消状态
                        },
                        fail: function() {
                            console.error('translateMarker 失败', app.getBeijingTime().ts)
                            nowTime = app.getBeijingTime();
                            that.setData({
                                nextMoveTs: nowTime.ts - 3000, //让定时器马上执行
                            })
                            // that.showBus({
                            //     ifFirstTime: true,
                            // });
                        }
                    })
                },
                fail: function(jimiGps_fail) {
                    console.error('showBus jimiGps_fail 失败', jimiGps_fail);
                    that.setData({
                        nextMoveTs: nowTime.ts - 3000, //让定时器马上执行
                    })
                }
            })
    },

    busOffline: function(e) {
        var that = this;
        app.db.collection('jimiGps').where({
            data: app.db.command.elemMatch({
                imei: app.globalData.imei
            })
        }).orderBy('beijingTs', 'desc').limit(1).get({
            success: function(jimiGps_data) {
                jimiGps_data = jimiGps_data.data[0].data;
                console.log('最后一条数据',jimiGps_data);
                carMarkerIndex = 0;
                that.setData({
                    ifStarted: true,
                    // nextMoveTs: nowTime.ts + 3000, //抬高时间,避免错误的第一步
                    mapMarkers: [{
                        id: carMarkerID,
                        longitude: jimiGps_data[0].longitude,
                        latitude: jimiGps_data[0].latitude,
                        iconPath: '/images/bus/pink.png',
                        width: 40,
                        height: 20,
                        rotate: 0,
                        anchor: { x: 0.5, y: 0.5 }
                    }],

                    mapCenter: {
                        latitude: jimiGps_data[0].latitude,
                        longitude: jimiGps_data[0].longitude,
                    },
                }, function() {

                    wx.showModal({
                        title: '提示',
                        content: '车载GPS未更新到新数据.',
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                console.log('用户点击确定')
                            }
                        }
                    })
                })


            },
            fail: function(jimiGps_fail) {
                console.error('busOffline jimiGps_fail 失败', jimiGps_fail);
            }

        })
    },

    getMapMarkerRotate: function(startPoint, endPoint) {
        var direction = Math.atan2(endPoint.longitude - startPoint.longitude,
            endPoint.latitude - startPoint.latitude) * 180 / Math.PI;

        //车icon原本角度就为车头朝右(东,90度),在此减去或者补偿
        direction = Math.round(direction > 90 ? direction - 90 : direction + 270);
        return direction;
    },

    mapMarkerTap: function(e) {},

    mapRegionChange: function(e) {},

    mapTap: function(e) {},

    mapControlTap: function(e) {},

    onHide: function() {
        console.log('onHide')
        this.setData({
            ifStarted: false,
        });
        clearInterval(ifMoving_interval);
    },

    onUnload: function() {
        console.log('onUnload')
        this.setData({
            ifStarted: false,
        });
        clearInterval(ifMoving_interval);
    },

    onShareAppMessage: function() {}
})